/**
 * 
 */
package com.scpii.universal.pns.dao.impl;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.hibernate.dao.impl.BaseDaoImpl;
import com.scpii.universal.pns.dao.PnsUserMessagesDao;
import com.scpii.universal.pns.entity.PnsUserMessages;

/**
 * genericWeb
 * 
 * @author acer 2012-7-5下午04:35:11
 */
@Repository
public class PnsUserMessagesDaoImpl extends BaseDaoImpl<PnsUserMessages, Long>
		implements PnsUserMessagesDao {

	@Override
	public void deleteByMessageId(Long messageId) {
		String hql = "DELETE FROM PnsUserMessages WHERE messageId=:messageId";
		Session session = getSession();
		Query query = session.createQuery(hql);
		query.setParameter("messageId", messageId);
		query.executeUpdate();
	}

	@Override
	public Integer getSendCount(Long messageId) {
		String schema = ResourceBundle.getBundle(
				GenericConstants.GLOBAL_PROPERTIES_PATH, Locale.getDefault())
				.getString("pns.schema");
		String sql = MessageFormat
				.format("SELECT COUNT(DISTINCT USER_ID)  FROM {0}.PNS_USER_MESSAGE_DEVICES UMD WHERE UMD.MESSAGE_STATUS IN (2, 3)  AND UMD.MESSAGE_ID = :messageId",
						schema);
		SQLQuery sqlQuery = getSession().createSQLQuery(sql);
		sqlQuery.setParameter("messageId", messageId);
		BigDecimal value = (BigDecimal) sqlQuery.uniqueResult();
		return value.intValue();
	}

	@Override
	public Integer getPushCount(Long messageId) {
		String schema = ResourceBundle.getBundle(
				GenericConstants.GLOBAL_PROPERTIES_PATH, Locale.getDefault())
				.getString("pns.schema");
		String sql = MessageFormat
				.format("SELECT \"COUNT\"(1) FROM {0}.PNS_USER_MESSAGES WHERE MESSAGE_ID=:messageId",
						schema);
		SQLQuery sqlQuery = getSession().createSQLQuery(sql);
		sqlQuery.setParameter("messageId", messageId);
		BigDecimal value = (BigDecimal) sqlQuery.uniqueResult();
		return value.intValue();
	}
}
